import { JSONEditor, JSONEditorPropsOptional } from "vanilla-jsoneditor";
import { useEffect, useRef } from "react";
import style from "./JSONEditorComponent.module.less";
export default function SvelteJSONEditor(
  props: JSONEditorPropsOptional & {
    height?: string | number;
    style?: React.CSSProperties;
  }
) {
  const refContainer = useRef<any>(null);
  const refEditor = useRef<any>(null);

  useEffect(() => {
    refEditor.current = new JSONEditor({
      target: refContainer.current,
      props: {
        mode: "text" as any,
        // 是否显示状态栏
        statusBar: false,
        onRenderMenu(items, context) {
          if (context.readOnly) {
            return [items[4]];
          }
          return [items[4], items[5], items[9], items[11], items[12]];
        },
      },
    });
    return () => {
      if (refEditor.current) {
        refEditor.current.destroy();
        refEditor.current = null;
      }
    };
  }, []);
  useEffect(() => {
    if (refEditor.current) {
      refEditor.current.updateProps(props);
    }
  }, [props]);

  return (
    <div
      className={`${
        props.navigationBar === false ? style.onlyStyle : ""
      } vanilla-jsoneditor-react`}
      ref={refContainer}
      style={{ height: props.height, ...(props.style || {}) }}
    ></div>
  );
}
